#nc--csv批量处理最终代码


import os
import xarray as xr
import numpy as np
import pandas as pd
import csv
import shutil



# 获取文件夹中的所有文件
nc_folder = r"F:\data\CMIP6\nc_ssp245"
nc_files = os.listdir(nc_folder)


j = 0
# 遍历每个文件
for nc_file in nc_files:
    print(j, nc_file)
    j += 1
    # 打开文件并将其看作是ds
    ds = xr.open_dataset(os.path.join(nc_folder, nc_file))

    csv_counter = 1  # 用于追踪CSV文件的计数器

    # 读取经纬度数据
    with open(r"F:\data\CMIP6\all9.csv", 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        next(reader)  # Skip the header row
        m = 0
        for row in reader:
            lon = float(row[0])  # Assuming the latitude is in the first column
            lat = float(row[1])  # Assuming the longitude is in the second column

            find_latindex = lat
            find_lonindex = lon

            sfcWind_tem = ds['sfcWind'].values
            lon_vals = ds['lon'].values
            lat_vals = ds['lat'].values

            lat_index = np.abs(lat_vals - find_latindex).argmin()
            lon_index = np.abs(lon_vals - find_lonindex).argmin()

            sfcWind_select = sfcWind_tem[:, lat_index, lon_index]
            time = ds['time'].values
            df = pd.DataFrame({'time': time, str(lat)+'_'+str(lon): sfcWind_select})

            # 创建对应的文件夹
            a, b, c, d, e, f, g = nc_file.split('_')
            g = g.replace('.nc', '')
            folder_path = os.path.join(r"F:\data\CMIP6\csv_ssp245", f"csv_{d}_{g}")
            os.makedirs(folder_path, exist_ok=True)

            # 动态创建CSV文件名
            csv_filename = os.path.join(folder_path, f"{csv_counter}_{lon}_{lat}.csv")

            # 将数据写入CSV文件
            df.to_csv(csv_filename, index=False)

            print(f"{m}  {row} ok")
            csv_counter += 1  # 增加CSV文件计数器
            m += 1

# 遍历每个文件并移动到指定文件夹
#for nc_file in nc_files:
    #shutil.move(os.path.join(nc_folder, nc_file), r"F:\data\CMIP6\history_nc")
# 开启D:\py-demo\csv_cf.py内的操作
#os.system("python D:\\py-demo\\csv_cf.py")